from urllib import request,parse
import json

def fanyi(str):  
    url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&sessionFrom='
    data = {'i':str,
            'rom':'AUTO',
            'to':'AUTO',
            'smartresult':'dict',
            'client':'fanyideskweb',
            'doctype':'json',
            'version':'2.1',
            'keyfrom':'fanyi.web',
            'action':'FY_BY_REALTIME',
            'typoResult':'true'
            }
    data = parse.urlencode(data)
    headers = {'Content-Length':len(data),
               'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36' 
               }
    try:
        req = request.Request(url,data=bytes(data,encoding="utf-8"),headers=headers)
        res = request.urlopen(req)
        str_json = res.read().decode('utf-8')

        #print(str_json)

        myjson = json.loads(str_json)

        print(myjson['translateResult'][0][0]['tgt'])
    except:
        print('error.')


if __name__=='__main__':
    while True:
        yourstr = input('请输入翻译内容：')
        if yourstr == 'q':
            break
        fanyi(yourstr)



